<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>员工列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline">
            <el-form-item label="公司">
              <el-select v-model="formInline.compId" @change="compDeplist" :disabled="isAll">
                <el-option label="无" value=""></el-option>
                <el-option v-for="item in compsList" :key="item.compId" :label="item.compName" :value="item.compId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="部门">
              <el-select v-model="formInline.deptId">
                <el-option label="无" value=""></el-option>
                <el-option v-for="ite in depList" :key="ite.deptId" :label="ite.deptName" :value="ite.deptId"></el-option>
              </el-select>
            </el-form-item>
            <!-- 员工姓名 -->
            <el-form-item label="姓名工号">
              <el-autocomplete
                v-model="formInline.userId"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入姓名"
                @select="handleSelect"
                clearable
              >
                <template slot-scope="{ item }">
                  <div class="selName">
                    <span>{{ item.userName }}</span>
                    <span>[{{ item.userId }}]</span>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="formInline.status">
                <el-option label="无" value=""></el-option>
                <el-option label="在职" value="0"></el-option>
                <el-option label="离职" value="1"></el-option>
                <el-option label="待入职" value="2"></el-option>
              </el-select>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <!-- 添加 -->
          <el-button
            v-if="btnAdd"
            type="success"
            size="medium"
            icon="el-icon-document-add"
            @click="addHandle"
          >添加</el-button>
          <!-- 删除 -->
          <el-button
            type="danger"
            size="medium"
            icon="el-icon-delete"
            @click="batchRemove"
            v-if="btnDel"
          >删除</el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="usersData"
          border
          @selection-change="selsChange"
          style="width: 100%"
          ref="usersData"
        >
          <!-- 全选 -->
          <el-table-column type="selection" width="40" fixed></el-table-column>
           <!-- 序号 -->
          <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
          <!-- 公司 -->
          <el-table-column sortable :show-overflow-tooltip="true" prop="compName" label="公司" width="150"></el-table-column>
          <!-- 部门 -->
          <el-table-column sortable :show-overflow-tooltip="true" prop="deptName" label="部门" width="150"></el-table-column>
           <!-- 归属地 -->
          <el-table-column prop="location" label="归属地" width="120"></el-table-column>
           <!-- 岗位 -->
          <el-table-column :show-overflow-tooltip="true" prop="position" label="岗位" width="150"></el-table-column>
          <!-- 员工工号 -->
          <el-table-column prop="userId" label="员工工号" width="120"></el-table-column>
          <!-- 员工姓名 -->
          <el-table-column prop="userName" label="员工姓名" width="120"></el-table-column>
          <!-- 员工性别 -->
          <el-table-column label="员工性别" width="120">
            <!-- 过滤判断  男：0 女：1 -->
            <template slot-scope="scope">{{ scope.row.sex === 0 ? '女' : '男'}}</template>
          </el-table-column>
          <!-- 在职状态 -->
          <el-table-column label="状态" width="150">
            <!-- 过滤判断 0 在职  1 离职 2 待入职 -->
            <template slot-scope="scope">
              <span v-if="scope.row.status === 0">在职</span>
              <span v-else-if="scope.row.status === 1">离职</span>
              <span v-else>待入职</span>
            </template>
          </el-table-column>
          <!-- 入职时间 -->
          <el-table-column label="入职时间" width="150">
            <template slot-scope="scope">{{ scope.row.joinTime | filterTime }}</template>
          </el-table-column>
           <!-- 离职时间 -->
          <el-table-column label="离职时间" width="150">
            <template slot-scope="scope">{{ scope.row.quitTime | filterTime }}</template>
          </el-table-column>
          <!-- 备注说明 -->
          <el-table-column prop="note" label="备注说明" :show-overflow-tooltip="true"></el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="300"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)" v-if="btnDel">删除</el-button>
              <!-- 修改 -->
              <el-button size="mini" @click="editHandle(scope.row, 1)" v-if="btnEdit">修改</el-button>
               <!-- 调岗 -->
              <el-button type="success" size="mini" @click="editHandle(scope.row, 2)" v-if="btnEdit && scope.row.status === 0">调岗</el-button>
               <!-- 离职 -->
              <el-button type="warning" size="mini" @click="editHandle(scope.row, 3)" v-if="btnEdit && scope.row.status === 0">离职</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
      <!-- 弹窗 新增or修改 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
      <!-- 添加、修改表单 -->
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-row :gutter="24">
            <el-col :span="12">
              <!-- 公司部门选择框子组件 -->
              <org-tree
                v-show="!isedit"
                v-model="editForm.compDept"
                :compdepts="compdepts"
                :comps="compsList"
                :selcpms="selcpmsVal"
                @selcompdepts="getCompDept"
              ></org-tree>
            </el-col>
            <el-col :span="12">
              <!-- 员工工号 -->
              <el-form-item label="员工工号" prop="userId">
                <el-input v-model="editForm.userId" auto-complete="off" :disabled="isedit"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName">
                <el-input v-model="editForm.userName" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 在职状态 -->
              <el-form-item label="状态" prop="status">
                <el-select style="width:100%;" v-model="editForm.status" :disabled="isedit">
                  <el-option label="在职" value="0">在职</el-option>
                  <el-option label="离职" value="1">离职</el-option>
                  <el-option label="待入职" value="2">待入职</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
             <el-col :span="12">
              <!-- 归属地 -->
              <el-form-item label="岗位" prop="position">
                <el-input v-model="editForm.position" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 入职时间 -->
              <el-form-item label="入职时间" prop="joinTime">
                <el-date-picker
                  v-model="editForm.joinTime"
                  type="date"
                  placeholder="选择日期"
                  style="width:100%;"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="归属地" prop="location">
                <el-input v-model="editForm.location" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 离职时间 -->
              <el-form-item label="离职时间" prop="quitTime">
                <el-date-picker
                  v-model="editForm.quitTime"
                  type="date"
                  placeholder="选择日期"
                  style="width:100%;"
                  :disabled="isedit"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 备注说明 -->
          <el-form-item label="备注说明" prop="note">
            <el-input
              type="textarea"
              placeholder="备注说明（20字以内）"
              maxlength="20"
              v-model="editForm.note"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 关闭弹窗 -->
          <el-button @click.native="dialogFormVisible=false">取消</el-button>
          <!-- 添加 清空表单初始数据 -->
          <el-button
            v-if="dialogStatus=='create'"
            type="primary"
            @click="createData"
          >添加</el-button>
          <!-- 修改获取表单初始数据 -->
          <el-button v-else type="primary" @click="editData">修改</el-button>
        </div>
      </el-dialog>

      <!-- 离职/调岗 -->
      <el-dialog :title="changeText" :visible.sync="modalVisible">
         <el-form ref="changeForm" :model="changeForm" label-width="80px" :rules="changeFormRules">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="员工工号" prop="userId">
                <el-input v-model="changeForm.userId" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName">
                <el-input v-model="changeForm.userName" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12" v-if="isOut">
              <!-- 公司部门选择框子组件 -->
              <org-tree
                v-model="changeForm.compDept"
                :compdepts="compdepts"
                :comps="compsList"
                :selcpms="selcpmsVal"
                @selcompdepts="getCompDept"
              ></org-tree>
            </el-col>
            <el-col :span="12">
              <!-- 具体日期 -->
              <el-form-item label="具体日期" prop="day">
                <el-date-picker
                  v-model="changeForm.day"
                  type="date"
                  placeholder="选择日期"
                  style="width:100%;"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 备注说明 -->
          <el-form-item label="备注说明" prop="note" v-if="!isOut">
            <el-input
              type="textarea"
              placeholder="备注说明（20字以内）"
              maxlength="20"
              v-model="changeForm.note"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 关闭弹窗 -->
          <el-button @click.native="modalVisible=false">取消</el-button>
          <!-- 修改获取表单初始数据 -->
          <el-button type="primary" @click="changeUser">确认</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';

// 引入公司部门选择徐建
import orgTree from '@/components/OrgTree/index.vue';

import { _debounce } from '@/public/debounce.js';

export default {
  name: 'users',
  // 注册组件
  components: {
    orgTree
  },

  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有公司
    this.getComp();

    // 获取所有部门
    this.getDept();

    // 获取所有员工
    this.getUsersAll();

    // 加载分页数据
    this.getUsersDataByPage();
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(value).format('YYYY-MM-DD');
    }
  },

  // 当前页面数据
  data () {
    return {
      isAll: false,

      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取所有公司
      compsList: [],

      // 获取所有用户
      usersAll: [],

      // 检索匹配
      restaurants: [],
      state: '',
      timeout: null,

      // 获取所有部门
      compdepts: [],

      // 获取公司部门选择框子组件选中值
      compDept: [],
      // 用户选择框子组件选中值
      getUser: [],

      // 根据所选公司获取对应部门
      depList: [],

      // 修改弹窗 - 公司部门子组件默认选中值
      selcpmsVal: [],

      // 搜索条件
      formInline: {
        compId: '',
        deptId: '',
        userId: '',
        status: '0'
      },

      // 列表数据
      usersData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',

      // 工号不允许修改
      isedit: true,

      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '添加信息'
      },
      // 弹窗是否显示
      dialogFormVisible: false,

      // 列表选中列
      sels: [],

      // 编辑界面输入框校验规则
      editFormRules: {
        userId: [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
        // password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        userName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
        // sex: [{ required: true, message: '请选择员工性别', trigger: 'change' }],
        status: [{ required: true, message: '请选择工作状态', trigger: 'change' }],
        // location: [{ required: true, message: '请输入归属地', trigger: 'blur' }],
        position: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
        // wechat: [{ required: true, message: '请输入企业微信账号', trigger: 'blur' }],
        joinTime: [{ required: true, message: '请选择入职时间', trigger: 'blur' }]
      },

      // 界面默认数据
      editForm: {
        compDept: [],
        userId: '',
        password: '',
        userName: '',
        sex: 0,
        status: 0,
        location: '',
        position: '',
        wechat: '',
        joinTime: '',
        note: '',
        email: '',
        tell: '',
        quitTime: '',
        birthday: ''
      },

      // 离职调岗弹出窗

      // 状态
      modalVisible: false,
      // 标题
      changeText: '',
      // 表单
      changeForm: {},

      changeFormRules: {
        day: [{ required: true, message: '请选择具体日期', trigger: 'change' }]
      },
      // 调岗/离职
      isOut: true
    };
  },

  mounted () {
    this.restaurants = this.loadAll();
  },

  methods: {
    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },

    // 获取所有公司
    getComp () {
      let _this = this;
      _this.$http.post('api/findAllCompNoPage').then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          for (let i = datas.length; i--;) {
            _this.compsList.push({
              compId: datas[i].compId,
              compName: datas[i].compName
            });
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有部门
    getDept () {
      let _this = this;
      // 获取部门列表
      _this.$http.post('api/findDeptByCompNoPage').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.compdepts = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 根据所选公司获取对应部门
    compDeplist () {
      let _this = this;

      let compId = _this.formInline.compId;
      // 重置部门
      _this.formInline.deptId = '';
      _this.depList = [];

      if (compId !== '') {
        let params = {
          compId: compId
        };
        // 获取对应部门ID的部门信息
        _this.$http.post('api/findDeptByCompNoPage', params).then(res => {
          let { code, datas } = res;
          // 判断Code状态
          if (code === 0) {
          // 匹配数据
            for (let i = datas.length; i--;) {
              _this.depList.push({
                deptId: datas[i].deptId,
                deptName: datas[i].deptName
              });
            }
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }
    },

    // 获取所有员工数据
    getUsersAll () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          for (let i = datas.length; i--;) {
            _this.usersAll.push({
              compName: datas[i].compName,
              deptName: datas[i].deptName,
              userId: datas[i].userId,
              userName: datas[i].userName
            });
          };
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 加载全部员工数据
    loadAll () {
      return this.usersAll;
    },

    // 自动检索匹配
    querySearchAsync (queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? restaurants.filter(_this.createStateFilter(queryString)) : restaurants;
      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },

    // 查询
    createStateFilter (queryString) {
      return (state) => {
        return (state.userName.indexOf(queryString) === 0);
      };
    },

    // 选中赋值
    handleSelect (item) {
      this.formInline.userId = item.userId;
    },

    // 查询
    selHandle: function () {
      let _this = this;
      // 收集请求数据
      let params = {
        userId: _this.formInline.userId,
        deptId: _this.formInline.deptId,
        compId: _this.formInline.compId,
        status: _this.formInline.status,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 根据员工ID 部门ID 公司ID查询分页数据
      _this.$http.raw('api/findAllUser', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.usersData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getUsersDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示新增界面
    addHandle: function () {
      let _this = this;
      // 允许添加工号
      _this.isedit = false;
      // 弹窗类型
      _this.dialogStatus = 'create';
      // 弹窗显示状态
      _this.dialogFormVisible = true;
      _this.compDept = '';
      // 初始化弹窗表单 公司部门选择框子组件选中数据
      _this.selcpmsVal = [];
      // 初始化新增界面默认数据
      _this.editForm = {
        compDept: '',
        userId: '',
        password: '',
        userName: '',
        sex: '0',
        status: '0',
        location: '',
        position: '',
        wechat: '',
        joinTime: '',
        note: '',
        email: '',
        tell: '',
        quitTime: '',
        birthday: ''
      };
    },

    // 获取公司部门选择框选中值
    getCompDept (data) {
      let _this = this;
      if (_this.isOut) {
        _this.compDept = data;
        _this.changeForm.compDept = data;
        _this.changeForm.location = data[1];
      }
      _this.editForm.compDept = data;
      _this.editForm.location = data[1];
    },

    // 添加
    createData: _debounce(function () {
      let _this = this;
      _this.$nextTick(() => {
        // 判断是否通过验证规则验证
        _this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求参数
            let params = {
              userName: _this.editForm.userName === null ? '' : _this.editForm.userName,
              userId: _this.editForm.userId === null ? '' : _this.editForm.userId,
              // 密码Md5转换
              password: _this.$md5('123456'),
              sex: 1,
              status: _this.editForm.status === null ? '' : _this.editForm.status,
              birthday: '',
              email: '',
              wechat: '',
              tell: '',
              location: _this.editForm.location === null ? '' : _this.editForm.location,
              position: _this.editForm.position === null ? '' : _this.editForm.position,
              joinTime: _this.editForm.joinTime === null ? '' : _this.editForm.joinTime,
              quitTime: _this.editForm.quitTime === null ? '' : _this.editForm.quitTime,
              mark: 1,
              createUserId: _this.$store.state.userinfo.userId,
              createTime: new Date(),
              updateUserId: _this.$store.state.userinfo.userId,
              updateTime: new Date(),
              deptIds: [{
                compId: _this.editForm.compDept[0],
                deptId: _this.editForm.compDept[2]
              }],
              note: _this.editForm.note === null ? '' : _this.editForm.note
            };
            // 获取选择用户工号
            let getUser = {
              userId: _this.editForm.userId
            };
            // 通过用户工号判断是否被占用
            _this.$http.post('api/checkUserByUserId', getUser).then(res => {
              let { code, datas } = res;
              // 判断Code状态
              if (code === 0) {
                if (datas) {
                  _this.$message({
                    message: '工号被占用！',
                    type: 'error'
                  });
                } else {
                  // 添加用户
                  _this.$http.raw('api/insertUser', params).then(res => {
                    let { code } = res;
                    // 判断Code状态
                    if (code === 0) {
                      _this.$message({
                        message: '添加成功！',
                        type: 'success'
                      });
                      _this.$refs['editForm'].resetFields();
                      _this.dialogFormVisible = false;
                      // 刷新列表
                      _this.getUsersDataByPage();
                      // 获取所有员工
                      _this.getUsersAll();
                    }
                  }).catch(err => {
                    if (err === undefined) {
                      _this.$message({
                        message: '服务器响应异常！',
                        type: 'error'
                      });
                      return false;
                    }
                  });
                }
              }
            }).catch(err => {
              if (err === undefined) {
                _this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    }, 200),

    // 显示编辑界面
    editHandle: function (row, type) {
      let _this = this;
      // 修改
      if (type === 1) {
        // 不允许修改工号
        _this.isedit = true;
        // 弹窗类型
        _this.dialogStatus = 'edit';
        // 弹窗显示状态
        _this.dialogFormVisible = true;

        // 公司部门选择框子组件初始选中值
        _this.selcpmsVal = [row.compName, row.deptName];

        // 弹出窗表单初始值赋值
        _this.editForm = Object.assign({}, row);

        // 弹出窗表单 - 公司部门选择框子组件初始值赋值
        _this.editForm.compDept = [
          row.compId,
          row.compName,
          row.deptId,
          row.deptName
        ];
        // 弹出窗表单 员工性别数据类型转换
        _this.editForm.sex = row.sex.toString();
        // 弹出窗表单 员工在职状态数据类型转换
        _this.editForm.status = row.status.toString();
      }
      // 调岗
      if (type === 2) {
        _this.changeText = '员工调岗';
        _this.modalVisible = true;
        _this.isOut = true;

        // 初始值赋值
        _this.selcpmsVal = [row.compName, row.deptName];

        sessionStorage.setItem('oldUserInfo', JSON.stringify(row));

        // 弹出窗表单初始值赋值
        _this.changeForm = {
          userId: row.userId,
          userName: row.userName,
          compDept: [
            row.compId,
            row.compName,
            row.deptId,
            row.deptName
          ],
          day: moment(new Date()).format('YYYY-MM-DD'),
          note: ''
        };
      }
      // 离职
      if (type === 3) {
        _this.changeText = '员工离职';
        _this.modalVisible = true;
        _this.isOut = false;

        sessionStorage.setItem('oldUserInfo', JSON.stringify(row));

        // 弹出窗表单初始值赋值
        _this.changeForm = {
          userId: row.userId,
          userName: row.userName,
          day: moment(new Date()).format('YYYY-MM-DD'),
          note: ''
        };
      }
    },
    // 调岗/离职
    changeUser: _debounce(function () {
      let _this = this;
      let oldrow = JSON.parse(sessionStorage.getItem('oldUserInfo'));
      _this.$nextTick(() => {
        // 判断是否通过验证规则验证
        _this.$refs['changeForm'].validate(valid => {
          if (valid) {
            // 调岗
            if (_this.isOut) {
              let changes = {
                userId: _this.changeForm.userId,
                userName: _this.changeForm.userName,
                type: 1,
                date: _this.changeForm.day,
                note: '原公司部门：' + oldrow.compName + ' [' + oldrow.deptName + ']' + ' 调岗后公司部门：' + _this.changeForm.compDept[1] + ' [' + _this.changeForm.compDept[3] + ']'
              };
              _this.$http.raw('api/insertPersonnel', changes).then(res => {
                let {code} = res;
                if (code === 0) {
                  let params = oldrow;
                  params.location = _this.changeForm.compDept[1];
                  params.compId = _this.changeForm.compDept[0];
                  params.compName = _this.changeForm.compDept[1];
                  params.deptId = _this.changeForm.compDept[2];
                  params.deptName = _this.changeForm.compDept[3];
                  // 修改用户信息
                  _this.$http.raw('api/updateUser', params).then(res => {
                    let { code } = res;
                    // 判断Code状态
                    if (code === 0) {
                      _this.$message({
                        message: '修改成功！',
                        type: 'success'
                      });
                      // 初始化弹出窗表单数据
                      _this.$refs['changeForm'].resetFields();
                      // 关闭弹窗
                      _this.modalVisible = false;
                      // 刷新列表
                      _this.getUsersDataByPage();
                      // 获取所有员工
                      _this.getUsersAll();
                    }
                  }).catch(err => {
                    if (err === undefined) {
                      _this.$message({
                        message: '服务器响应异常！',
                        type: 'error'
                      });
                      return false;
                    }
                  });
                }
              }).catch(err => {
                if (err === undefined) {
                  _this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
            }
            // 离职
            if (!_this.isOut) {
              let changes = {
                userId: _this.changeForm.userId,
                userName: _this.changeForm.userName,
                type: 2,
                date: moment(_this.changeForm.day).format('YYYY-MM-DD'),
                note: '员工已离职'
              };

              _this.$http.raw('api/insertPersonnel', changes).then(res => {
                let { code } = res;

                if (code === 0) {
                  let params = oldrow;
                  params.status = 1;
                  params.quitTime = moment(_this.changeForm.day).format('YYYY-MM-DD');

                  // 修改用户信息
                  _this.$http.raw('api/updateUser', params).then(res => {
                    let { code } = res;
                    // 判断Code状态
                    if (code === 0) {
                      let userAsset = {
                        userId: _this.changeForm.userId
                      };

                      _this.$http.post('api/updateAssetStatus', userAsset).then(res => {
                        let {code, datas} = res;
                        if (code === 0) {
                          if (datas[0].assetCode !== null) {
                            for (let i = datas.length; i--;) {
                              setTimeout(() => {
                                let nstat = datas[i].assetStatus;
                                if (nstat === 1) {
                                  nstat = '占用';
                                }
                                if (nstat === 2) {
                                  nstat = '空闲';
                                }
                                if (nstat === 3) {
                                  nstat = '维修';
                                }
                                if (nstat === 4) {
                                  nstat = '报废';
                                }
                                if (nstat === 5) {
                                  nstat = '停用';
                                }
                                let changes = {
                                  assetCode: datas[i].assetCode,
                                  operation: '离职变更',
                                  note: '归属人' + _this.changeForm.userName + ' [' + _this.changeForm.userId + ']已离职，状态原始值：' + nstat + ' 变更后：空闲'
                                };
                                _this.$http.raw('api/insertAssetRecord', changes).then().catch(err => {
                                  if (err === undefined) {
                                    _this.$message({
                                      message: '服务器响应异常！',
                                      type: 'error'
                                    });
                                    return false;
                                  }
                                });
                              }, 200);
                            }

                            _this.$message({
                              message: '修改成功！',
                              type: 'success'
                            });
                            // 初始化弹出窗表单数据
                            _this.$refs['changeForm'].resetFields();
                            // 关闭弹窗
                            _this.modalVisible = false;
                            // 刷新列表
                            _this.getUsersDataByPage();
                            // 获取所有员工
                            _this.getUsersAll();
                          } else {
                            _this.$message({
                              message: '修改成功！',
                              type: 'success'
                            });
                            // 初始化弹出窗表单数据
                            _this.$refs['changeForm'].resetFields();
                            // 关闭弹窗
                            _this.modalVisible = false;
                            // 刷新列表
                            _this.getUsersDataByPage();
                            // 获取所有员工
                            _this.getUsersAll();
                          }
                        }
                      }).catch(err => {
                        if (err === undefined) {
                          _this.$message({
                            message: '服务器响应异常！',
                            type: 'error'
                          });
                          return false;
                        }
                      });

                      // _this.$message({
                      //   message: '修改成功！',
                      //   type: 'success'
                      // });
                      // // 初始化弹出窗表单数据
                      // _this.$refs['changeForm'].resetFields();
                      // // 关闭弹窗
                      // _this.modalVisible = false;
                      // // 刷新列表
                      // _this.getUsersDataByPage();
                      // // 获取所有员工
                      // _this.getUsersAll();
                    }
                  }).catch(err => {
                    if (err === undefined) {
                      _this.$message({
                        message: '服务器响应异常！',
                        type: 'error'
                      });
                      return false;
                    }
                  });
                }
              }).catch(err => {
                if (err === undefined) {
                  _this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
            }
          }
        });
      });
    }, 200),
    // 修改
    editData: _debounce(function () {
      let _this = this;
      _this.$nextTick(() => {
        // 判断是否通过验证规则验证
        _this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求数据
            let params = {
              id: _this.editForm.id,
              userName: _this.editForm.userName === null ? '' : _this.editForm.userName,
              userId: _this.editForm.userId === null ? '' : _this.editForm.userId,
              // 密码Md5转换
              password: _this.editForm.password,
              sex: _this.editForm.sex,
              status: _this.editForm.status === null ? '' : _this.editForm.status,
              birthday: _this.editForm.birthday,
              email: _this.editForm.email,
              wechat: _this.editForm.wechat,
              tell: _this.editForm.tell,
              location: _this.editForm.location === null ? '' : _this.editForm.location,
              position: _this.editForm.position === null ? '' : _this.editForm.position,
              joinTime: _this.editForm.joinTime === null ? '' : _this.editForm.joinTime,
              quitTime: _this.editForm.quitTime === null ? '' : _this.editForm.quitTime,
              mark: 1,
              createUserId: _this.$store.state.userinfo.userId,
              createTime: new Date(),
              updateUserId: _this.$store.state.userinfo.userId,
              updateTime: new Date(),
              duId: _this.editForm.duId,
              compId: _this.editForm.compDept[0],
              compName: _this.editForm.compDept[1],
              deptId: _this.editForm.compDept[2],
              deptName: _this.editForm.compDept[3],
              note: _this.editForm.note === null ? '' : _this.editForm.note
            };
            // 修改用户信息
            _this.$http.raw('api/updateUser', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                _this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                // 初始化弹出窗表单数据
                _this.$refs['editForm'].resetFields();
                // 关闭弹窗
                _this.dialogFormVisible = false;
                // 刷新列表
                _this.getUsersDataByPage();
                // 获取所有员工
                _this.getUsersAll();
              }
            }).catch(err => {
              if (err === undefined) {
                _this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    }, 200),

    // 删除
    handleDelete (data) {
      let _this = this;
      // 二次删除确认
      _this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 收集请求参数
        let params = {
          id: data.id
        };
        // 根据数据ID删除对应用户信息
        _this.$http.post('api/delUser', params).then(res => {
          let { code } = res;
          if (code === 0) {
            _this.$message({
              type: 'success',
              message: '删除成功！'
            });
            // 刷新列表
            _this.getUsersDataByPage();
            // 获取所有员工
            _this.getUsersAll();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 全选、单选、多选
    selsChange: function (sels) {
      this.sels = sels;
    },

    // 批量删除
    batchRemove: function () {
      let _this = this;
      // 判断是否选择数据
      if (!_this.sels.length) {
        _this.$message.warning('您还没选择任何数据！');
        return;
      }
      // 二次删除确认
      _this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 修改状态，逻辑删除
        let params = [];
        // 获取选中数据ID集合
        _this.sels.map(item => {
          return params.push(item.id);
        });
        // 删除对应ID用户信息
        _this.$http.raw('api/batchDelUser', params).then(res => {
          let { code } = res;
          if (code === 0) {
            _this.$message({
              type: 'success',
              message: '批量删除成功！'
            });
            // 刷新列表
            _this.getUsersDataByPage();
            // 获取所有员工
            _this.getUsersAll();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        _this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 刷新页面数据
    getUsersDataByPage () {
      let _this = this;

      // 分地区数据
      let location = _this.$store.state.userinfo.location;
      if (_this.formInline.compId === null || _this.formInline.compId === undefined || _this.formInline.compId === '') {
        if (location === '南京') {
          _this.isAll = true;
          _this.formInline.compId = 'STSNJ';
          _this.compDeplist();
        }
        if (location === '北京') {
          _this.isAll = true;
          _this.formInline.compId = 'STSBJ';
          _this.compDeplist();
        }
        if (location === '上海') {
          _this.isAll = true;
          _this.formInline.compId = 'STSSH';
          _this.compDeplist();
        }
        if (location === '广州') {
          _this.isAll = true;
          _this.formInline.compId = 'STSGZ';
          _this.compDeplist();
        }
        if (location === '全部') {
          _this.isAll = false;
          _this.formInline.compId = '';
        }
      }
      // 收集请求参数
      let params = {
        userId: _this.formInline.userId === null ? '' : _this.formInline.userId,
        deptId: _this.formInline.deptId === null ? '' : _this.formInline.deptId,
        compId: _this.formInline.compId === null ? '' : _this.formInline.compId,
        status: _this.formInline.status === null ? '0' : _this.formInline.status,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };

      // 获取分页数据
      _this.$http.raw('api/findAllUser', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.usersData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getUsersDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getUsersDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getUsersDataByPage();
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
